import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";

import { useUserStore } from "@/store/modules/user";
import { computed, watch } from "vue";
import { useRouter } from "vue-router";
import {
  userLogin,
  verifyEmail,
  registerUser,
  sendEmail,
  getUserAvatar
  // addBlogInfo
} from "@/api/user/user";
import { ElMessage } from "element-plus";
import { validateEmail, validatePassword } from "@/utils/validate";
import { scrollTo } from "@/utils/scorllTo";
import useMouseBan from "@/hooks/useMouseBan";
// import { QNURL } from "@/config/urlConfig";

export function useLogin() {
  const userStore = useUserStore();
  const router = useRouter();

  useMouseBan();

  const storeRememberPwd = computed(() => userStore.rememberPwd);
  const userLoginInfo = computed(() => userStore.userLoginInfo);

  interface LoginRuleForm {
    username?: string;
    password?: string;
  }

  interface RegiesterRuleForm {
    nickname?: string;
    username?: string;
    password?: string;
    comfirmPassword?: string;
  }

  interface VerifyRuleForm {
    code?: string;
  }

  const userId = ref("");
  const nickName = ref("");

  const loginRef = ref();
  const loading = ref(false);
  const emailInSend = ref(false);

  // 登入
  const loginRuleFormRef = ref<FormInstance>();
  const loginRuleForm = reactive<LoginRuleForm>({
    username: userLoginInfo.value.username,
    password: userLoginInfo.value.password
  });

  // 注册
  const regiesterRuleFormRef = ref<FormInstance>();
  const regiesterRuleForm = reactive<RegiesterRuleForm>({
    nickname: "",
    username: "",
    password: "",
    comfirmPassword: ""
  });

  // 验证
  const verifyFormRef = ref<FormInstance>();
  const verifyForm = reactive<VerifyRuleForm>({
    code: ""
  });

  const validateEmailFun = (rule: any, value: any, callback: any) => {
    if (validateEmail(value)) {
      callback();
    } else {
      callback(new Error("邮箱不合法！"));
    }
  };

  const validatePwdFun = (rule: any, value: any, callback: any) => {
    if (validatePassword(value)) {
      callback();
    } else {
      callback(
        new Error("密码长度需大于等于6且小于12，并且包含字母和特殊符号！")
      );
    }
  };

  const loginRules = reactive<FormRules<LoginRuleForm>>({
    username: [
      { required: true, message: "请输入邮箱", trigger: "blur" },
      { validator: validateEmailFun, trigger: "blur" }
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { validator: validatePwdFun, trigger: "blur" }
    ]
  });

  const regiesterRules = reactive<FormRules<RegiesterRuleForm>>({
    nickname: [
      { required: true, message: "请输入昵称", trigger: "blur" },
      {
        min: 2,
        max: 6,
        message: "昵称长度需要在2到5个字符之间",
        trigger: "blur"
      }
    ],
    username: [
      { required: true, message: "请输入邮箱", trigger: "blur" },
      { validator: validateEmailFun, trigger: "blur" }
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { validator: validatePwdFun, trigger: "blur" }
    ],
    comfirmPassword: [
      { required: true, message: "请输入确认密码", trigger: "blur" },
      { validator: validatePwdFun, trigger: "blur" }
    ]
  });

  const verifyRules = reactive<FormRules<VerifyRuleForm>>({
    code: [
      { required: true, message: "请输入验证码", trigger: "blur" },
      { min: 6, max: 100, message: "格式错误", trigger: "blur" }
    ]
  });

  const rememberPwd = ref(storeRememberPwd.value);

  const isLogin = ref(true);
  const regiesterBoxTop = ref(460);
  const loginBoxOpacy = ref(1);
  const regiesterBoxLeft = ref(0);

  const goRegister = () => {
    isLogin.value = !isLogin.value;
    regiesterBoxTop.value = 0;
    loginBoxOpacy.value = 0;

    scrollTo(loginRef.value.clientHeight, 500, loginRef.value);
  };

  const goLogin = () => {
    if (loading.value) {
      ElMessage.warning("账号注册中，请等待...");
      return;
    }
    scrollTo(0, 500, loginRef.value);
    regiesterBoxTop.value = 460;
    loginBoxOpacy.value = 1;
  };

  async function regiester() {
    if (loading.value) return;
    regiesterRuleFormRef.value &&
      regiesterRuleFormRef.value.validate(async valid => {
        if (valid) {
          if (
            regiesterRuleForm.password !== regiesterRuleForm.comfirmPassword
          ) {
            ElMessage.error("两次输入的密码不一致");
            return;
          }
          try {
            loading.value = true;
            const res = await registerUser({
              username: regiesterRuleForm.username,
              nickname: regiesterRuleForm.nickname,
              password: regiesterRuleForm.password
            });
            loading.value = false;
            if (res.code === 200) {
              userId.value = res.data?.userId || "";
              nickName.value = res.data?.nickName || "";
              regiesterBoxLeft.value = -630;
              scrollTo(loginRef.value.clientHeight * 2, 500, loginRef.value);

              // 发送邮件
              emailInSend.value = true;
              const emailSendRes = await sendEmail({ id: userId.value });

              if (emailSendRes.code === 200) {
                emailInSend.value = false;
              }
            }
          } catch (err) {
            console.error(err);
          }
        } else {
          ElMessage({
            message: "表单不完整",
            type: "error"
          });
        }
      });
  }

  async function verifyHandle() {
    verifyFormRef.value &&
      verifyFormRef.value.validate(async valid => {
        if (valid) {
          try {
            loading.value = true;
            const res = await verifyEmail({
              code: verifyForm.code,
              id: userId.value
            });
            loading.value = false;

            if (res.code === 200) {
              // await addBlogInfoFun();

              ElMessage.success("验证通过");

              loginRuleForm.username = regiesterRuleForm.username;
              loginRuleForm.password = regiesterRuleForm.password;

              regiesterRuleForm.username = "";
              regiesterRuleForm.nickname = "";
              regiesterRuleForm.password = "";
              regiesterRuleForm.comfirmPassword = "";

              regiesterBoxTop.value = 460;
              loginBoxOpacy.value = 1;
              scrollTo(0, 500, loginRef.value);

              setTimeout(() => {
                regiesterBoxLeft.value = 0;
              }, 1000);
            }
          } catch (err) {
            console.error(err);
          }
        } else {
          ElMessage({
            message: "未输入验证码",
            type: "error"
          });
        }
      });
  }

  // 登入处理函数
  const btnClick = () => {
    loginRuleFormRef.value &&
      loginRuleFormRef.value.validate(async valid => {
        if (valid) {
          if (rememberPwd.value) {
            userStore.SET_USER_LOGIN_INFO({
              username: loginRuleForm.username,
              password: loginRuleForm.password
            });
          } else {
            userStore.SET_USER_LOGIN_INFO({
              username: "",
              password: ""
            });
          }

          loading.value = true;
          const res = await userLogin({
            username: loginRuleForm.username,
            password: loginRuleForm.password
          });
          loading.value = false;

          if (res.code == 200 && typeof res.data === "object") {
            const obj = {
              username: res.data.username,
              userId: res.data.userId,
              nickname: res.data.nickname,
              avatar: res.data.avatar
            };

            userStore.SET_TOKEN(res.data?.token);
            userStore.SET_USER_INFO(obj);
            userStore.SET_ROLES(res.data.roles);

            // addBlogInfoFun(obj.userId, obj.username);

            router.replace({
              path: "/"
            });

            ElMessage.success("登录成功");
          } else {
            ElMessage.error(res.msg);
          }
        } else {
          ElMessage({
            message: "表单不完整",
            type: "error"
          });
          return false;
        }
      });
  };

  const userAvatar = ref("4a21acb7f8e146f2b5e110e59799c35e");

  async function getUserAvatarFun(val: string) {
    try {
      const res = await getUserAvatar({ username: val });

      if (res.msg) {
        userAvatar.value = res.msg;
      } else {
        userAvatar.value = "4a21acb7f8e146f2b5e110e59799c35e";
      }
    } catch (err) {
      console.error(err);
    }
  }

  watch(
    () => loginRuleForm.username,
    val => {
      if (validateEmail(val as string)) {
        console.log(val);
        getUserAvatarFun(val as string);
      }
    },
    { deep: true, immediate: true }
  );

  const rememberPwdChange = () => {
    userStore.SET_REMEMBER_PWD(rememberPwd.value);
  };

  // async function addBlogInfoFun() {
  //   try {
  //     await addBlogInfo({
  //       userId: userId.value,
  //       bg: "",
  //       description: "天道酬勤",
  //       notice: "这里用来展示通知！！！",
  //       title: nickName.value + "的博客，点击修改"
  //     });
  //   } catch (err) {
  //     console.error(err);
  //   }
  // }

  return {
    verifyRules,
    regiesterRules,
    loginRules,
    loginRuleForm,
    regiesterRuleForm,
    loginRuleFormRef,
    regiesterRuleFormRef,
    verifyFormRef,
    rememberPwd,
    regiesterBoxTop,
    loginBoxOpacy,
    regiesterBoxLeft,
    verifyForm,
    loading,
    loginRef,
    emailInSend,
    userAvatar,
    goLogin,
    regiester,
    goRegister,
    rememberPwdChange,
    btnClick,
    verifyHandle
  };
}
